package service

import (
	"oa-system/internal/api/request"
	"oa-system/internal/model"
	"oa-system/internal/repository"
	"oa-system/pkg/errors"
)

type DepartmentService interface {
	GetAllDepartments(page, pageSize int, name string) ([]model.Department, int64, error)
	GetDepartmentByID(id uint) (*model.Department, error)
	CreateDepartment(req *request.CreateDepartmentRequest) (*model.Department, error)
	UpdateDepartment(id uint, req *request.UpdateDepartmentRequest) (*model.Department, error)
	DeleteDepartment(id uint) error
}

type departmentService struct {
	repo repository.DepartmentRepository
}

func NewDepartmentService(repo repository.DepartmentRepository) DepartmentService {
	return &departmentService{repo: repo}
}

func (s *departmentService) GetAllDepartments(page, pageSize int, name string) ([]model.Department, int64, error) {
	return s.repo.GetAllDepartments(page, pageSize, name)
}

func (s *departmentService) GetDepartmentByID(id uint) (*model.Department, error) {
	return s.repo.GetDepartmentByID(id)
}

func (s *departmentService) CreateDepartment(req *request.CreateDepartmentRequest) (*model.Department, error) {
	department := &model.Department{
		Name:     req.Name,
		ParentID: req.ParentID,
		Icon:     req.Icon,
	}
	return s.repo.CreateDepartment(department)
}

func (s *departmentService) UpdateDepartment(id uint, req *request.UpdateDepartmentRequest) (*model.Department, error) {
	department, err := s.repo.GetDepartmentByID(id)
	if err != nil {
		return nil, errors.NewNotFoundError("部门不存在", err)
	}

	department.Name = req.Name
	department.ParentID = req.ParentID
	department.Icon = req.Icon

	return s.repo.UpdateDepartment(department)
}

func (s *departmentService) DeleteDepartment(id uint) error {
	if _, err := s.repo.GetDepartmentByID(id); err != nil {
		return errors.NewNotFoundError("部门不存在", err)
	}
	return s.repo.DeleteDepartment(id)
}
